<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="navbar">
			<view class="tn-icon-left" @click="left"></view>
			<view class="navbar-title">{{user.userId!==0?'他':'我'}}的主页</view>
			<view class="edit-icon">{{user.userId===0?'编辑':''}}</view>
		</view>

		<!-- 用户信息 -->
		<view class="user-info">
			<view class="avatar-container">
				<image class="avatar" :src="user.avatarUrl" mode="aspectFill" />
			</view>
			<view class="text-container">
				<text class="nickname">{{ user.nickName }}</text>
			</view>
			<view class="follow-button-container" v-if="user.userId !== 0">
				<button class="follow-button" @click="toggleFollow">
					{{ isFollowed ? '已关注' : '关注' }}
				</button>
			</view>
		</view>
		<tn-toast ref="toast"></tn-toast>
		<view class="tabs">
			<view class="tab-item active">商品</view>
		</view>

		<!-- 动态列表 -->
		<view class="content-list">
			<view class="content-item" v-for="(item, index) in contentList" :key="index">
				<view class="content-details" @click="dian(item.goods.id)">
					<text class="item-title">{{ item.goods.name }}</text>
					<image class="item-image" :src="item.goods.picUrl" mode="aspectFill" />
					<text class="item-text">{{ item.goods.brief }}</text>
				</view>
				<view class="content-purchase" v-if="user.userId !== 0">
					<text style="margin-right: auto;color: #FF4400;">￥{{item.goods.counterPrice}}</text>
					<tn-button size="sm" shape="icon" class="tn-icon-reduce-circle" :fontSize="60"
						@click="decreaseQuantity(index)" v-show="purchaseQuantity[index]>0" />
					<text v-show="purchaseQuantity[index]>0"
						style="margin-left: 4px;margin-right: 2px;">{{purchaseQuantity[index]}}</text>
					<tn-button size="sm" shape="icon" backgroundColor="#00c298" class="tn-icon-add-circle"
						:disabled="purchaseQuantity[index]==contentList[index].goodsProduct.number" :fontSize="60"
						@tap="increaseQuantity(index)" />
				</view>
			</view>
		</view>

		<view class="bottom-bar" v-if="user.userId !== 0">
			<view class="total-info">
				<text>已选商品 {{ totalItems }} 件</text>
				<text class="total-amount">￥{{ totalAmount }}</text>
			</view>
			<button v-show="cartItems.length!=0" class="settlement-btn" @click="confirmOrder">结算</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				user: {
					userId: 0,
					avatarUrl: 'https://example.com/avatar.jpg',
					nickName: null,
					bio: '这个人很懒，什么都没留下',
				},
				contentList: [],
				isFollowed: false,
				purchaseQuantity: [],
				totalItems: 0,
				totalAmount: 0,
				cartItems: []
			};
		},
		onLoad(option) {
			const userInfo = uni.getStorageSync('userInfo');
			if (option.userId === undefined || option.userId == userInfo.id) {
				this.user.nickName = userInfo.nickName;
				this.user.avatarUrl = userInfo.avatarUrl;
				this.getUserGoodsList(userInfo.id);
			} else {
				this.getSeller(option.userId);
				this.getUserGoodsList(option.userId);
				this.isfollowings(option.userId)
			}
		},
		methods: {
			showToast(title, icon = 'none') {
				uni.showToast({
					title,
					icon
				});
			},
			confirmOrder() {
				uni.request({
					url: this.baseUrl + "/wx/companyInfo/getCompanyInfo",
					method: 'GET',
					data: {
						userId: uni.getStorageSync('userInfo').id
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data.errno === 0 && res.data.data) {
							this.buyerCompany = res.data.data;
							// 所有数据加载完成
							this.loading = false;
							let info = {
								"cartItems": this.cartItems,
								"userId": this.user.userId
							}
							uni.navigateTo({
								url: `/pages/Information/orderConfirmationPage/orderConfirmationPage?data=${encodeURIComponent(JSON.stringify(info))}`,
							});
						} else {
							this.showToast('请完善公司信息后重试');
							this.loading = false;
							return
						}
					},
					fail: (error) => {
						console.error('获取买家公司信息失败:', error);
						this.showToast('获取买家信息失败');
						this.loading = false;
					}
				});


			},

			decreaseQuantity(index) {
				if (this.isLogin()) {
					this.$refs.toast.show({
						content: '请登录后重试',
						duration: 1500
					});
					return;
				}

				const currentQuantity = this.purchaseQuantity[index];
				if (currentQuantity <= 0) {
					this.$refs.toast.show({
						content: '数量不能低于0',
						duration: 1500
					});
					return;
				}

				// 减少商品数量
				this.$set(this.purchaseQuantity, index, currentQuantity - 1);
				this.totalItems -= 1;
				this.totalAmount -= this.contentList[index].goodsProduct.price;

				const product = this.contentList[index];

				const cartItemIndex = this.cartItems.findIndex(
					(item) => item.good.goods.id === product.goods.id
				);

				if (cartItemIndex !== -1) {
					// 如果商品数量减到0，则从购物车移除
					if (this.purchaseQuantity[index] === 0) {
						this.cartItems.splice(cartItemIndex, 1);
					} else {
						// 否则更新数量和总价
						this.cartItems[cartItemIndex].quantity -= 1;
						this.cartItems[cartItemIndex].price -= product.goodsProduct.price;
					}
				}
			},
			increaseQuantity(index) {
				if (this.isLogin()) {
					this.$refs.toast.show({
						content: '请登录后重试',
						duration: 1500
					});
					return;
				}

				const product = this.contentList[index];
				const currentQuantity = this.purchaseQuantity[index];
				const maxStock = product.goodsProduct.number;

				if (currentQuantity >= maxStock) {
					this.$refs.toast.show({
						content: '只有这么多库存了',
						duration: 1500
					});
					return;
				}

				this.$set(this.purchaseQuantity, index, currentQuantity + 1);
				this.totalItems += 1;
				this.totalAmount += product.goodsProduct.price;

				const cartItem = {
					good: product,
					quantity: this.purchaseQuantity[index],
					price: product.goodsProduct.price
				};

				const existingCartItemIndex = this.cartItems.findIndex(
					(item) => item.good.goods.id === product.goods.id
				);

				if (existingCartItemIndex === -1) {
					this.cartItems.push(cartItem);
				} else {
					this.cartItems[existingCartItemIndex].quantity += 1;
					this.cartItems[existingCartItemIndex].price += product.goodsProduct.price;
				}
			},
			dian(id) {
				uni.navigateTo({
					url: `/pages/index/productDetails/productDetails?id=${id}`,
				});
			},
			getSeller(userId) {
				const that = this;
				uni.request({
					url: `${this.baseUrl}/wx/user/getUser?userId=${userId}`,
					success(res) {
						const data = res.data.data;
						if (Object.keys(data).length !== 0) {
							that.user.userId = data.user.id;
							that.user.nickName = data.user.nickname;
							that.user.avatarUrl = data.user.avatar;
						}
					},
				});
			},
			getUserGoodsList(userId) {
				const that = this;
				uni.request({
					url: `${this.baseUrl}/wx/goods/getUserGoodsList/${userId}`,
					method: 'GET',
					success(res) {
						that.contentList = res.data.data;
						let c = new Array(res.data.data.length).fill(0);
						that.purchaseQuantity = c
					},
				});
			},
			left() {
				uni.navigateBack({
					delta: 1,
				});
			},
			toggleFollow() {
				this.isFollowed = !this.isFollowed;
				if (!this.isLogin()) {
					const userInfo = uni.getStorageSync('userInfo');
					console.log(this.isFollowed);
					if (this.isFollowed) {
						uni.request({
							url: `${this.baseUrl}/wx/follow/follow/${this.user.userId}/${userInfo.id}`,
							method: 'POST',
							data: {
								followingName: this.user.nickName,
								followingAvatar: this.user.avatarUrl
							},
							success() {
								console.log(111);
							}
						});
					} else {
						uni.request({
							url: `${this.baseUrl}/wx/follow/unfollow/${this.user.userId}/${userInfo.id}`,
							method: 'POST'
						});
					}
				} else {
					this.$refs.toast.show({
						content: '请登录后重试',
						duration: 1500
					})
				}
			},
			isfollowings(userId) {
				const userInfo = uni.getStorageSync('userInfo');
				let that = this
				uni.request({
					url: `${this.baseUrl}/wx/follow/status/${userInfo.id}/${userId}`,
					method: 'GET',
					success: (res) => {
						that.isFollowed = res.data.data
					}
				});
			},
			isLogin() {
				const userInfo = uni.getStorageSync('userInfo');
				if (userInfo === "" || userInfo.id === undefined) {
					return true
				} else {
					return false
				}
			}
		}
	};
</script>

<style scoped>
	.bottom-bar {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #fff;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
		z-index: 999;
	}

	.total-info {
		flex: 1;
		margin-right: 20rpx;
	}

	.total-amount {
		font-weight: bold;
		color: #00c298;
	}

	.settlement-btn {
		background-color: #ffd700;
		color: #fff;
		padding: 1rpx 45rpx;
		border: none;
		border-radius: 40rpx;
		font-size: 25rpx;
	}

	.settlement-btn:active {
		background-color: #ffd700cc;
	}



	.container {
		background-color: #ffe6b3;
		padding: 20rpx;
		margin-top: 20px;
		padding-bottom: 120rpx;
		/* 根据底部工具栏的高度调整 */
	}

	.navbar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		background-color: #ffd700;
		color: #ffffff;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		margin-top: 20px;
	}

	.navbar-title {
		font-size: 36rpx;
		font-weight: bold;
	}

	.back-icon,
	.edit-icon {
		font-size: 32rpx;
		color: #ffffff;
	}

	.user-info {
		display: flex;
		align-items: center;
		margin-top: 100rpx;
		padding: 20rpx;
		background-color: #fff3e0;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.avatar-container {
		margin-right: 20rpx;
	}

	.avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 60rpx;
		border: 2rpx solid #ffe6b3;
	}

	.text-container {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.nickname {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 10rpx;
	}

	.follow-button-container {
		margin-left: 20rpx;
	}

	.follow-button {
		background-color: #ffd700;
		color: #ffffff;
		padding: 10rpx 25rpx;
		font-size: 20rpx;
		border-radius: 40rpx;
		border: none;
	}

	.bio {
		padding: 20rpx;
		background-color: #fff3e0;
		margin-top: 20rpx;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.tabs {
		display: flex;
		justify-content: space-around;
		background-color: #fff3e0;
		padding: 20rpx;
		margin-top: 20rpx;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.tab-item {
		flex: 1;
		text-align: center;
		font-size: 30rpx;
		color: #666666;
	}

	.tab-item.active {
		color: #6c838c;
		border-bottom: 4rpx solid #ffd700;
		line-height: 50rpx;
	}

	.content-list {
		margin-top: 10rpx;
		display: flex;
		flex-wrap: wrap;
	}

	.content-list :nth-child(even) {
		margin-left: 2%
	}

	.content-item {
		width: 49%;
		margin-bottom: 20rpx;
		padding: 20rpx;
		background-color: #fff3e0;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.content-details {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.item-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 10rpx;
	}

	.item-image {
		width: 80%;
		height: 300rpx;
		margin-top: 20rpx;
		margin-right: 10px;
		border-radius: 10rpx;
	}

	.item-text {
		font-size: 28rpx;
		color: #333333;
		margin-top: 20rpx;
	}

	.content-purchase {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		width: auto;
	}
</style>